package com.blb.community_admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.blb.community_admin.Annotation.Log;
import com.blb.community_admin.entity.SysDictData;
import com.blb.community_admin.entity.SysDictType;
import com.blb.community_admin.service.ISysDictDataService;
import com.blb.community_admin.service.ISysDictTypeService;
import com.blb.community_admin.util.EasyExcelUtil;
import com.blb.community_admin.util.FuzzyResearchUtil;
import com.blb.community_admin.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hkp
 * 字典类型管理的控制层
 */
@RestController
@Api(tags = "字典类型模块")
public class SysDictTypeController {

    @Resource
    private ISysDictTypeService sysDictTypeService;

    @Resource
    private ISysDictDataService sysDictDataService;

    /**
     * 分页查询字典类型
     *
     * @param current
     * @return
     */
    @ApiOperation("分页查询")
    @GetMapping("/SysDictTypes/page")
    public ResponseResult<IPage<SysDictType>> selectPage(Integer current) {
        return ResponseResult.ok(sysDictTypeService.selectPage(current, 10));
    }

    /**
     * 根据字典名称，字典类型，状态进行模糊查询
     *
     * @param current
     * @param dictName
     * @param dictType
     * @param status
     * @return
     */
    @ApiOperation("根据字典名称，字典类型，状态进行模糊查询")
    @GetMapping("/SysDictTypes/page/fuzzy")
    public ResponseResult<IPage<SysDictType>> selectPageByFuzzy(Integer current, Integer size, String dictName, String dictType, String status, String createTime) {
        /**
         * @param startTime 开始时间
         * @param endTime 结束时间
         */
        String startTime = null;
        String endTime = null;
        if (StringUtils.isNotEmpty(createTime)) {
            String[] split = createTime.split(",");
            startTime = split[0];
            endTime = split[1];
        }
        dictName = FuzzyResearchUtil.addPercent(dictName);
        dictType = FuzzyResearchUtil.addPercent(dictType);
        status = FuzzyResearchUtil.addPercent(status);
        return ResponseResult.ok(sysDictTypeService.selectByFuzzy(current, size, dictName, dictType, status, startTime, endTime));
    }

    /**
     * 修改字典类型
     *
     * @param sysDictType
     * @return
     */
    @Log(module = "字典类型",operationType = 2,requestMethod = "PUT")
    @ApiOperation("修改字典类型")
    @PutMapping("/SysDictType")
    public ResponseResult<String> update(@RequestBody SysDictType sysDictType) {
        sysDictType.setUpdateTime(LocalDateTime.now());
//        先根据参数查询有没有对应的dictType的数据
        SysDictType one = sysDictTypeService.getOne(new QueryWrapper<SysDictType>().lambda().eq(SysDictType::getDictType, sysDictType.getDictType()));
        if (one == null) {
            return ResponseResult.ok("不能修改数据类型");
        }
        List<SysDictData> list = sysDictDataService.list(new QueryWrapper<SysDictData>().lambda().eq(SysDictData::getDictType, sysDictType.getDictType()));
        if (list.size() != 0) {
            return ResponseResult.ok("该表中有数据，不支持修改");
        }
        sysDictTypeService.updateById(sysDictType);
        return ResponseResult.ok("OK");
    }

    /**
     * 根据字典编号删除
     *
     * @param id
     * @param dictType
     * @return
     */
    @Log(module = "字典类型",operationType = 3,requestMethod = "DELETE")
    @ApiOperation("根据字典编号删除")
    @DeleteMapping("/SysDictType/{id}")
    public ResponseResult<String> deleteById(@PathVariable Long id, String dictType) {
        List<SysDictData> list = sysDictDataService.list(new QueryWrapper<SysDictData>().lambda().eq(SysDictData::getDictType, dictType));
        if (list.size() != 0) {
            return ResponseResult.ok("该表中有数据，不支持删除");
        }
        sysDictTypeService.removeById(id);
        return ResponseResult.ok("ok");
    }

    /**
     * 新增
     *
     * @param sysDictType
     * @return
     */
    @Log(module = "字典类型",operationType = 1,requestMethod = "POST")
    @PostMapping("/SysDictType")
    public ResponseResult<String> add(@RequestBody SysDictType sysDictType) {
//        类型不能重复否则不能新增
        SysDictType one = sysDictTypeService.getOne(new QueryWrapper<SysDictType>().lambda().eq(SysDictType::getDictType, sysDictType.getDictType()));
        if (one != null) {
            return ResponseResult.ok("字典类型已存在，添加失败");
        }
        sysDictType.setCreateTime(LocalDateTime.now());
        sysDictTypeService.save(sysDictType);
        return ResponseResult.ok("OK");
    }


    /**
     * 查询所有DictType字段(用于输入提示)
     *
     * @return
     */
    @ApiOperation("查询所有DictType字段")
    @GetMapping("/SysDictType")
    public ResponseResult<List<SysDictType>> selectAllName() {
        List<SysDictType> list = sysDictTypeService.list(null);
        return ResponseResult.ok(list);
    }

    /**
     * 导出
     *
     * @param sysDictTypes
     * @return
     */
    @Log(module = "字典类型",operationType = 5,requestMethod = "POST")
    @ApiOperation("导出")
    @PostMapping("/SysDictType/export")
    public ResponseEntity<ByteArrayResource> export(@RequestBody List<SysDictType> sysDictTypes) throws IOException {
        String path = EasyExcelUtil.write("字典管理", SysDictType.class, sysDictTypes);
        ResponseEntity<ByteArrayResource> download = EasyExcelUtil.download(path);
        return download;
    }

    @Log(module = "字典类型",operationType = 3,requestMethod = "DELETE")
    @ApiOperation("根据字典编号批量删除")
    @DeleteMapping("/SysDictType/delete")
    public ResponseResult<String> deleteByIds(@RequestBody List<SysDictType> selections) {
        int num = 0;
        for (SysDictType sysDictType : selections) {
            List<SysDictData> list = sysDictDataService.list(new QueryWrapper<SysDictData>().lambda().eq(SysDictData::getDictType, sysDictType.getDictType()));
            num += list.size();
        }
        if (num != 0) {
            return ResponseResult.ok("该表中有数据，不支持删除");
        }
        ArrayList<Long> dictIds = new ArrayList<>();
        selections.stream().forEach(sysDictType -> {
            dictIds.add(sysDictType.getDictId());
        });
        sysDictTypeService.removeByIds(dictIds);
        return ResponseResult.ok("ok");
    }

}
